﻿using DotNetty.Codecs.Http.WebSockets;
using DotNetty.Transport.Channels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WebSocketChatServer
{
    public class BanabaService
    {
        /// <summary>
        /// 通道处理的上下文
        /// </summary>
        private IChannelHandlerContext ctx;

        /// <summary>
        /// 姓名
        /// </summary>
        private string name;

        /// <summary>
        /// 客户端在线列表
        /// </summary>
        public static Dictionary<string, BanabaService> banabaDic = new Dictionary<string, BanabaService>();

        public BanabaService(IChannelHandlerContext ctx, string name)
        {
            this.ctx = ctx;
            this.name = name;
        }

        /// <summary>
        /// 客户端注册(登录/上线)
        /// </summary>
        /// <param name="requestId"></param>
        /// <param name="banaba"></param>
        /// <returns></returns>
        public static bool regist(string requestId, BanabaService banaba)
        {
            // 客户端唯一标志符为空,或者该客户端已经注册,那么不需要重复注册
            if (string.IsNullOrWhiteSpace(requestId) || banabaDic.ContainsKey(requestId))
                return false;  // 返回false,代表注册失败

            banabaDic.Add(requestId, banaba);
            return true;
        }

        /// <summary>
        /// 客户端登出
        /// </summary>
        /// <param name="requestid"></param>
        /// <returns></returns>
        public static bool logout(string requestid)
        {
            // 客户端唯一标志符为空,或者该客户端未注册
            if (string.IsNullOrEmpty(requestid) || !banabaDic.ContainsKey(requestid))
                return false;

            // 客户端下线
            banabaDic.Remove(requestid);
            return true;
        }

        /// <summary>
        ///  服务端发送消息
        /// </summary>
        /// <param name="msg"></param>
        public void send(RequestMsg msg)
        {
            // ctx.Removed:判断IChannelHandlerContext是否被移除
            if (this.ctx == null || this.ctx.Removed)
                throw new Exception("尚未握手成功,无法向客户端发送websocket消息");

            this.ctx.WriteAndFlushAsync(new TextWebSocketFrame(msg.ToString()));
        }

        /// <summary>
        /// 分发消息(下线)
        /// </summary>
        /// <param name="requestId"></param>
        public static void notifyOutline(string requestId)
        {
            foreach (KeyValuePair<string, BanabaService> item in banabaDic)
            {
                RequestMsg msg = new RequestMsg();
                msg.ServiceId = Code.OUTLINE;
                msg.RequestId = requestId;
                try
                {
                    item.Value.send(msg);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("发送消息给客户端时异常:" + ex.Message);
                }
            }
        }

    }
}
